package com.weiiew.imageservice.service;

import com.twelvemonkeys.image.ResampleOp;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Description
 * @Author 魏锴
 * @Date 2024/7/23
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ImageServiceImpl implements ImageService {

    private static final int[] sizes = new int[]{40, 64, 100, 128, 256};
    private static final String imagePath = "F:/作业/工厂管理器/resources";
    private static byte[] readAllBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, bytesRead);
        }
        buffer.flush();
        return buffer.toByteArray();
    }
    public boolean saveNetImage(String type, String version, String fileName, String imageUrl){
        try {
            // 0. 校验并修正 URL 格式
            if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://")) {
                imageUrl = "https://" + imageUrl;
            }

            // 1. 打开 HTTP 连接
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(10000);

            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new IOException("HTTP请求失败，响应码: " + responseCode);
            }

            // 使用try-with-resources自动关闭流
            try (InputStream inputStream = connection.getInputStream()) {
                byte[] bytes = readAllBytes(inputStream); // 使用自定义方法
                return saveBytesToStorage(type, version, fileName, bytes);
            }
        } catch (IOException e) {
            String errorMsg = String.format("下载图片失败 | URL: %s | 错误: %s", imageUrl, e.getMessage());
            return false;
        }
    }
    @Override
    public boolean saveImage(String type, String version, String fileName, MultipartFile file) {
        try {
            return saveBytesToStorage(type, version, fileName, file.getBytes());
        } catch (IOException e) {
            System.out.println("e.getMessage() = " + e.getMessage());
            return false;
        }
    }


    public boolean saveImage(String type, String version, String fileName, File file) {
        try {
            return saveBytesToStorage(type, version, fileName, Files.readAllBytes(file.toPath()));
        } catch (IOException e) {
            System.out.println("e.getMessage() = " + e.getMessage());
            return false;
        }
    }

    private boolean saveBytesToStorage(String type, String version, String fileName, byte[] bytes) throws IOException {
        System.out.println("ImagePath = " + imagePath);
        // 创建InputStream对象
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        // 使用ImageIO读取InputStream
        BufferedImage image = ImageIO.read(inputStream);
        for (int size : sizes) {
            String prePath = imagePath + '/' + type + '/' + version + '/' + size;
            File dir = new File(prePath);
            if (!dir.exists()) dir.mkdirs();
            this.saveScaledImage(size, prePath + '/' + fileName + ".png", image);
        }
        return true;
    }
    @Override
    public boolean removeImage(String type, String version, String fileName) {
        for (int size : sizes) {
            String prePath = String.join(File.separator, imagePath, type, version, String.valueOf(size),fileName) + ".png";
            Path path = Paths.get(prePath);
            System.out.println("删除图片" + path);
            try {
                Files.deleteIfExists(path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    private void saveScaledImage(int size, String path, BufferedImage image) throws IOException {
        ResampleOp sampler = new ResampleOp(size, size, ResampleOp.FILTER_LANCZOS);
        BufferedImage outputImage = sampler.filter(image, null);
        ImageIO.write(outputImage, "png", new File(path));
        System.out.println("图片格式：" + size + "存储成功, 存储路径:" + path);
    }
}
